package com.gitee.cui.security.netty.https;

import com.gitee.cui.config.SystemConfig;
import com.gitee.cui.ssl.SSLContextHelper;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.*;
import java.io.BufferedInputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 安全的Http客户端实现
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/5 17:07
 **/
@Slf4j
public class SecureHttpClient {

    public static void sendRequest(String path) throws Exception {
        SSLContext context = SSLContextHelper.createClientSSLContext();
        SSLSocketFactory factory = context.getSocketFactory();

        HttpsURLConnection.setDefaultSSLSocketFactory(factory);
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String host, SSLSession sslSession) {
                if (SystemConfig.SOCKET_SERVER_IP.equals(host)) {
                    return true;
                } else {
                    log.error("主机名称校验失败：{}", SystemConfig.SOCKET_SERVER_IP);
                    return false;
                }
            }
        });

        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        int code = connection.getResponseCode();
        if (code < 400) {
            //输入流
            BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
            StringBuffer sb = new StringBuffer();
            int total = 0;
            int length = 0;
            byte[] buffer = new byte[1024 * 8];
            while ((length = inputStream.read(buffer)) != -1) {
                sb.append(new String(buffer));
                total += length;
                log.info("共完成传输字节数：{}", total);
            }
            log.info("echo = {}", sb);
        }
    }
}
